<?php
$myDir = dirname(__FILE__) . "/";
require_once($myDir."../autoload.php");
if ( $argc == 1 || $argv[1] == "--help" ) {
  die( "\n\tUsage: php ".$argv[0]." [CONTROLLER_NAME] [ACTION_NAME] [NUM_PARAMS] [FULL_PATH_TO_PROJECT]\n\n");  
}

$contrName = $argv[1];
$actionName= $argv[2];
$numArgs   = $argv[3];
$path      = $argv[4];

require_once($path . "user_autoload.php");
$newContrConf=WebUtils::addActionToConfig($contrName, $actionName, $numArgs);
file_put_contents(Conf::get('MY_HOME'). "config/web/controllers_config.php", $newContrConf);

$reflContr = new ReflectionClass($contrName);
try {
  $reflContr->getMethod($actionName);
  die("Action " . $actionName . " has already been defined for the controller ". $contrName. "\n");
}
 catch(ReflectionException $re) {}

$smarty = new SmartyExt();
$smarty->right_delimiter = ":]";
$smarty->left_delimiter = "[:";
$smarty->assign("actionName", $actionName);
$smarty->assign("numArgs", $numArgs); 
$actionCont = $smarty->fetch($myDir . 'action.dry');

//new $contrName();

//die();
$lineBeforeLast = $reflContr->getEndLine()-0;

$fp = fopen($path."controllers/".$contrName.".php", "r");

$linesCount = 0;
$newContr = "";
while( $line = fgets($fp) ) {
  $linesCount++;
  if ($linesCount == $lineBeforeLast) {
    $newContr .= "\n\n" .$actionCont;
  }
  $newContr .= $line;
}
fclose($fp);

file_put_contents($path."controllers/".$contrName.".php", $newContr);


